/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Web;

import Control.printers;
import DA.*;
import Entity.*;
import javax.servlet.RequestDispatcher;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author theInterloper
 */
@WebServlet(name = "shopControl", urlPatterns = {"/shopControl"})
public class shopControl extends HttpServlet {
    

    private static Artist readArtistFromSession(HttpServletRequest request) {
        Artist artist = new Artist();
        HttpSession session = request.getSession();
        //session.setAttribute("artistInfo", artist);
        artist = (Artist) session.getAttribute("artistInfo");
        if(artist!= null){
            Control.printers.printArtist(artist);
        } 
        return artist;
    }

    private static Customer readCustomerFromSession(HttpServletRequest request) {
        Customer customer = new Customer();
        HttpSession session = request.getSession();
        //session.setAttribute("artistInfo", artist);
        customer = (Customer) session.getAttribute("customerInfo");
        if(customer!= null){
            Control.printers.printCustomer(customer);
        }
        return customer;
       
    }

    public static void loadAllArtistsToSession(HttpServletRequest request, HttpServletResponse response) throws SQLException {           
        System.out.println("trip artist");
        HttpSession session = request.getSession();
         if(session.getAttribute("artistcollection")== null){
            System.out.println("no artist data found loading data");
            Collection artistCollection = new ArrayList<Artist>();
            int[] maxMinArray = {7,7};
            maxMinArray = common.getMaxMinID("artist");
            int max = maxMinArray [0];
            int min = maxMinArray [1];

            for (int i = min; i < max; i++) {
                Artist artist = new Artist();
                artist = artistDA.read (i);
                artistCollection.add(artist);
                System.out.println((max - i) + " artists remaining to read");
            }
            //HttpSession session = request.getSession();
            session.setAttribute("artistcollection", artistCollection);
        }
         System.out.println(" artist data found, no loading necessary ");
    }

    public static void loadAllItemsToSession(HttpServletRequest request, HttpServletResponse response) throws SQLException { 
        System.out.println("trip item");
        HttpSession session = request.getSession();
        if(session.getAttribute("itemcollection")== null){
            System.out.println("no item data found loading data");
            Collection itemCollection = new ArrayList<Item>();
            int[] maxMinArray = {7,7};
            maxMinArray = common.getMaxMinID("item");
            int max = maxMinArray [0];
            int min = maxMinArray [1];

            for (int i = min; i < max; i++) {
                Item item = new Item();
                item = itemDA.read (i);
                itemCollection.add(item);
                System.out.println((max - i) + " items remaining to read");
            }
            session.setAttribute("itemcollection", itemCollection);    
        }
        System.out.println(" item data found, no loading necessary ");
        
    }
    //loadInterestedCustomersToSession
    public static void loadInterestedCustomersToSession (HttpServletRequest request, HttpServletResponse response) throws SQLException { 
        System.out.println("trip interested");
        HttpSession session = request.getSession();
        if(session.getAttribute("interestedcollection")== null){
            System.out.println("no interested data found loading data");
            Collection interestedCollection = new ArrayList<Item>();
            int[] maxMinArray = {7,7};
            maxMinArray = common.getMaxMinID("interested");
            int max = maxMinArray [0];
            int min = maxMinArray [1];

            for (int i = min; i < max; i++) {
                Interested interested = new Interested();
                interested = interestedDA.read (i);
                interestedCollection.add(interested);
                System.out.println((max - i) + " interested remaining to read");
            }
            session.setAttribute("interestedcollection", interestedCollection);    
        }
        System.out.println(" interested data found, no loading necessary ");
        
    }

    public static void loadAllCustomersToSession(HttpServletRequest request, HttpServletResponse response) throws SQLException {
        System.out.println("trip customer");
        HttpSession session = request.getSession();
        if(session.getAttribute("customercollection")== null){
            System.out.println("no customer data found loading data");
            Collection customerCollection = new ArrayList<Customer>();
            int[] maxMinArray = {7,7};
            maxMinArray = common.getMaxMinID("customer");
            int max = maxMinArray [0];
            int min = maxMinArray [1];

            for (int i = min; i < max; i++) {
                Customer customer = new Customer();
                customer = customerDA.read (i);
                customerCollection.add(customer);
                System.out.println((max - i) + " customers remaining to read");
            }
            session.setAttribute("customercollection", customerCollection);    
        }
        System.out.println(" customer data found, no loading necessary ");
        
    }
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        System.out.println("**********SERVLET TRIGGERED**********");
        
        HttpSession session = request.getSession(); 
        
        
        
        System.out.println("The controller returned a value of: " + request.getParameter("control"));
        
        int option = Integer.parseInt(request.getParameter("control"));
        


                    switch(option){
                        case 0: break;
                        case 1:
                            
        //<editor-fold defaultstate="collapsed" desc="login check">

            String userName = request.getParameter("username");
            System.out.println("The username entered is: " + userName);
            String passWord = request.getParameter("password");
            System.out.println("The password entered is: " + passWord);
            int loginControl = common.artistLoginContoller(userName, passWord);

            session.setAttribute("logincontrol", loginControl);

            //User != Artist. Username: False. Password: False, Search Customer DB
            if(loginControl == 3){
                loginControl = common.customerLoginController(userName, passWord);     
            }
            loginTester(loginControl);

            if(loginControl == 1){
                Artist artist = new Artist();
                artist = artistDA.readByUserName(userName);

                writeArtistToSession(artist, request);
                boolean isLoggedIn = true;
                //HttpSession session = request.getSession();
                session.setAttribute("artistisloggedin", new Boolean(isLoggedIn));
                testSession(request);
            }
            if(loginControl == 4){
                Customer customer = new Customer();
                customer = customerDA.readByUserName(userName);
                System.out.println("**********************The customer returned after validation is:");
                printers.printCustomer(customer);
                System.out.println("****************************************************************");
                writeCustomerToSession(customer, request);
                boolean isLoggedIn = true;
                //HttpSession session = request.getSession();
                session.setAttribute("customerisloggedin", new Boolean(isLoggedIn));
                testSession(request);
            }

            System.out.println("The username entered is: " + userName);
            System.out.println("The password entered is: " + passWord);
            System.out.println("The validator returned a value of:" + loginControl);
            
            RequestDispatcher rd1 = getServletContext().getRequestDispatcher("/index.jsp");
            rd1.forward(request, response);
            
        //</editor-fold>
        
                        break;
                        case 2:
       
        //<editor-fold defaultstate="collapsed" desc="item registration">
        
        Artist artist = new Artist(); 
        artist = (Artist)session.getAttribute("artistInfo");
        
        Item item = new Item();
        
        item.setNAME(request.getParameter("itemname"));
        item.setQUANTITY(Integer.parseInt(request.getParameter("itemquantity")));
        item.setPRICE(Double.parseDouble(request.getParameter("itemprice")));
        item.setDESCRIPTION(request.getParameter("itemdescription"));
        item.setARTIST_ARTISTID(artist.getID());
        
        itemDA.write(item); 
        
        RequestDispatcher rd2 = getServletContext().getRequestDispatcher("/index.jsp");
        rd2.forward(request, response);
                            //</editor-fold>
        
                        break;
                        case 3:
                            
        //<editor-fold defaultstate="collapsed" desc="go to artist registration">
                            
        RequestDispatcher rd3 = getServletContext().getRequestDispatcher("/registerArtist.jsp");
        rd3.forward(request, response);
        
                            //</editor-fold>
                            
                        break;
                        case 4:
                            
        //<editor-fold defaultstate="collapsed" desc="go to customer registration">
        
        RequestDispatcher rd4 = getServletContext().getRequestDispatcher("/registerCustomer.jsp");
        rd4.forward(request, response);
                            
                            //</editor-fold>
                            
                        break;
                        case 5:
                            
        //<editor-fold defaultstate="collapsed" desc="artist registration">
        Artist writeArtist = new Artist();
        writeArtist.setUSERNAME(request.getParameter("username"));
        writeArtist.setPASSWORD(request.getParameter("password"));
        writeArtist.setFIRSTNAME(request.getParameter("firstname"));
        writeArtist.setSECONDNAME(request.getParameter("secondname"));
        writeArtist.setPHONE(request.getParameter("phonenumber"));
        writeArtist.setEMAIL(request.getParameter("emailaddress"));
        writeArtist.setADDRESS1(request.getParameter("address1"));
        writeArtist.setADDRESS2(request.getParameter("address2"));
        writeArtist.setADDRESS3(request.getParameter("address3"));
        writeArtist.setDESCRIPTION(request.getParameter("artistdescription"));
        
        artistDA.write(writeArtist);
        
        RequestDispatcher rd5 = getServletContext().getRequestDispatcher("/index.jsp");
        rd5.forward(request, response);
                            
                            //</editor-fold>
                            
                        break;
                        case 6:
                            
        //<editor-fold defaultstate="collapsed" desc="customer registration">
        Customer writeCustomer = new Customer();
        writeCustomer.setUSERNAME(request.getParameter("username"));
        writeCustomer.setPASSWORD(request.getParameter("password"));
        writeCustomer.setFIRSTNAME(request.getParameter("firstname"));
        writeCustomer.setSECONDNAME(request.getParameter("secondname"));
        writeCustomer.setPHONE(request.getParameter("phonenumber"));
        writeCustomer.setEMAIL(request.getParameter("emailaddress"));
        writeCustomer.setADDRESS1(request.getParameter("address1"));
        writeCustomer.setADDRESS2(request.getParameter("address2"));
        writeCustomer.setADDRESS3(request.getParameter("address3"));
       
        customerDA.write(writeCustomer);
       
        RequestDispatcher rd6 = getServletContext().getRequestDispatcher("/index.jsp");
        rd6.forward(request, response);
                            
                            //</editor-fold>
                            
                        break;
                        case 7:
                            
        //<editor-fold defaultstate="collapsed" desc="go to individual artist">
                            Collection artistCollection = new ArrayList<Item>();
                            int artistid = Integer.parseInt(request.getParameter("artistid"));
                            artistCollection = (Collection) session.getAttribute("artistcollection");
                            Iterator it = artistCollection.iterator();
                            while (it.hasNext()) {
                                Artist findArtist = new Artist();
                                findArtist = (Artist) it.next();
                                if(findArtist.getID()== artistid){
                                    session.setAttribute("selectedartist", findArtist);
                                }
                            }
                            RequestDispatcher rd7 = getServletContext().getRequestDispatcher("/individualartist.jsp");
                            rd7.forward(request, response);
                            //</editor-fold>
                            
                        break;
                        case 8:
                            
        //<editor-fold defaultstate="collapsed" desc="write interested">
                            int itemId = Integer.parseInt(request.getParameter("itemid"));
                            int artistId = Integer.parseInt(request.getParameter("artistid"));
                            Customer customer = new Customer();
                            customer = (Customer)session.getAttribute("customerInfo");
                            
                            Interested interested = new Interested();
                            interested.setITEMID(itemId);
                            interested.setCUSTOMERID(customer.getID());
                            interested.setARTISTID(artistId);
                            
                            interestedDA.write(interested);
                            
                            RequestDispatcher rd8 = getServletContext().getRequestDispatcher("/allitems.jsp");
                            rd8.forward(request, response);
                            
                            //</editor-fold>
                            
                        break;
                        case 9:
                            
                        break;
                        case 10:
                            
                        break;
                        case 11:
                            
                        default:
                            System.out.println("not a valid option");
                            break;
                    }
        
        
        
        
        

        
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet shopControl</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet shopControl at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {            
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(shopControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(shopControl.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void loginTester(int loginControl) {
        if(loginControl == 1){
            System.out.println("User = Artist. Username: True. Password: True");    
        }
        if(loginControl == 2){
            System.out.println("User = Artist. Username: True. Password: False");
        }
        if(loginControl == 3){
            System.out.println("User != Artist. Username: False. Password: False");
        }
        if(loginControl == 4){
            System.out.println("User = Customer. Username: True. Password: True");
        }
        if(loginControl == 5){
            System.out.println("User = Customer. Username: True. Password: False");    
        }
        if(loginControl == 6){
            System.out.println("User != Customer or Artist. Username: False. Password: False");
        }
    }

    private void writeArtistToSession(Artist artist, HttpServletRequest request) {
        System.out.println("Servlet write artist to session triggered");
        HttpSession session = request.getSession();
        session.setAttribute("artistInfo", artist);
        
    }

    private void writeCustomerToSession(Customer customer, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("customerInfo", customer);
    }

    private void testSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Boolean isLoggedIn;
        isLoggedIn = (Boolean)session.getAttribute("isloggedin");
        System.out.println("The value of the retirved boolean is " + isLoggedIn);
    }
}
